package com.atguigu.gulimall.auth.controller;

/**
 * @Classname OAuth2Controller
 * @Description TODO
 * @Date 2024/7/11 17:23
 * @Created by 369502594
 */

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.to.SocialUserTo;
import com.atguigu.common.vo.MemberRespVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登陆请求
 */
@ConfigurationProperties(prefix = "gitee.oauth")
@Controller
@Data
@Slf4j
public class OAuth2Controller {
    private String clientId;

    private String clientSecret;

    private String redirectUri;


    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> headers = new HashMap<>();
        Map<String, String> querys = new HashMap<>();
        querys.put("grant_type", "authorization_code");
        querys.put("code", code);
        querys.put("client_id", clientId);
        querys.put("redirect_uri", redirectUri);
        querys.put("client_secret", clientSecret);
        Map<String, String> bodys = new HashMap<>();
        // 1、根据code换取accessToken
        HttpResponse responsePost = HttpUtils.doPost("https://gitee.com", "/oauth/token", "POST", headers, querys, bodys);

        // 2、处理
        if(responsePost.getStatusLine().getStatusCode() == 200){
            // 获取到了 accessToken
            String json = EntityUtils.toString(responsePost.getEntity());
            SocialUserTo socialUserTo = JSON.parseObject(json, SocialUserTo.class);
            if(socialUserTo != null && StringUtils.hasLength(socialUserTo.getAccessToken())){
                querys.clear();
                querys.put("access_token", socialUserTo.getAccessToken());
                HttpResponse responseGet = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "GET", headers, querys);
                //
                if(responseGet.getStatusLine().getStatusCode() == 200){
                    json = EntityUtils.toString(responseGet.getEntity());
                    SocialUserTo user = JSON.parseObject(json, SocialUserTo.class);
                    BeanUtils.copyProperties(user, socialUserTo, "accessToken", "tokenType", "expiresIn", "refreshToken", "scope", "createdAt");
                    R r = memberFeignService.login(socialUserTo);
                    if(r.getCode() == 0){
                        json = JSON.toJSONString(r.get("data"));
                        MemberRespVo vo = JSON.parseObject(json, MemberRespVo.class);
                        log.info("登录成功，用户信息：{}", vo.toString());
                        // 1、第一次使用session；命令浏览器保存卡号。JSESSIONID这个cookie
                        // 以后浏览器访问哪个网站就会带上这个网站的cookie
                        // 子域之间；gulimall.com  auth.gulimall.com  order.gulimall.com
                        // 发卡的时候，即使是子域系统发的卡，也能让父域直接使用
                        // TODO 1、默认发的令牌。session=dadad。作用域：当前域；（解决子域共享问题）
                        // TODO 2、使用JSON的序列化方式来序列化对象到Redis中
                        session.setAttribute("loginUser", vo);
                        return "redirect:http://gulimall.com";
                    }
                }
            }
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
